package com.shitu.base.rn;

import android.app.Activity;

import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.module.annotations.ReactModule;


/**
 * Created by kissonchan on 2017/8/2.
 */
@ReactModule(name = EventModule.NAME)
public class EventModule extends ReactContextBaseJavaModule {

    public static final String NAME = "RNEventModule";

    public EventModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return NAME;
    }

    @ReactMethod
    public void emit(String uniqueID, ReadableMap params, Promise promise) {
        Activity activity = getCurrentActivity();
        if (activity != null) {
            if (activity instanceof BaseRNActivity) {
                ((BaseRNActivity) activity).handleEvent(uniqueID, params, promise);
            } else {
                if (promise != null) {
                    promise.reject("ActivityTypeError", "activity must be extend ReactBaseActivity");
                }
            }
        } else {
            if (promise != null) {
                promise.reject("ActivityDestroyedError", "activity has been destroyed!");
            }
        }
    }

    @ReactMethod
    public void emitClose(String uniqueID, Promise promise) {
        Activity activity = getCurrentActivity();
        if (activity != null) {
            activity.finish();
        }
    }

}

